package controllers;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import controllers.Application;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;

import models.Cliente;
import models.LogsTarefa;
import models.StatusTarefaEnum;
import models.Tarefa;
import models.TipoTarefaEnum;
import models.TipoUsuarioEnum;
import play.db.DB;
import play.db.jpa.GenericModel.JPAQuery;
import play.db.jpa.JPA;
import play.mvc.Controller;

public class Tarefas extends Controller {

	static long idTarefaAtual;
	private static Application ap = new Application();

	public static void quadroTarefasFuncionario() throws SQLException {
		
		
		List<Tarefa> tarefas = new ArrayList<Tarefa>();
		String user = session.get("usuario");
		String tipoUsuario = ap.checkAdmin();

		ap.verificarAutenticacao();
		
		javax.persistence.Query query = JPA.em().createQuery(
				"select t from Tarefa t inner join " +
				"t.usuario u " +
				"where u.username = '" + user + "'" +
						"and t.status = 'Pausado' or " +
						"t.status = 'Iniciado'  " +
						"order by t.prioridade desc");
				
		//u.id = t.usuario
		tarefas = query.getResultList();

		render(tarefas, user, tipoUsuario);
	}

	public static void concluirTarefa(long id) throws SQLException {
		Tarefa tarefa = Tarefa.find("id", id).first();
		
		tarefa.setStatus(StatusTarefaEnum.Concluido);
		tarefa.save();
		
		quadroTarefasFuncionario();
	}

	// Detalhes da tarefa cadastrada
	public static void detalhesTarefa(long id) throws SQLException {
		Application ap = new Application();
		String user = session.get("usuario");
		String tipoUsuario = ap.checkAdmin();
		
		Tarefa tarefa = Tarefa.find("id", id).first();
		List<LogsTarefa> log = LogsTarefa.find(
				"tarefa_id = ? order by data desc", id).fetch();
		
		
		if(tipoUsuario.equals("funcionario")){
			tarefa.setNovaTarefa(false);
			tarefa.save();
		}
	
		
		
		render(tarefa, log, user, tipoUsuario);
	}
	
	public static void iniciarTarefa(long id_tarefa, long id_usuario)
			throws SQLException {
		DB.execute("exec iniciarTarefa @id_Usuario = " + id_usuario + ", @id_Tarefa = " + id_tarefa);
		quadroTarefasFuncionario();
	}

	public static void pausarTarefa(long id) throws SQLException{
		 DB.execute("exec PausarTarefa  @id_tarefa = " + id);
		quadroTarefasFuncionario();
	}
}
